//
//  MeBaseViewController.swift
//  DollarBuy
//
//  Created by 郑东喜 on 2016/11/7.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  登陆、注册、忘记密码、修改密码、退出统一基类

import UIKit



class MeBaseViewController: UIViewController {
    

    lazy var manager = AFHTTPSessionManager()
    
    lazy var zdxmanager = NetTool()
    
    
    static let shared : MeBaseViewController = MeBaseViewController()

    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    //点击屏幕撤销编辑
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}

// MARK:- 返回主视图
extension MeBaseViewController {
    func backToMain() -> Void {
        //延时1s执行
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1*NSEC_PER_SEC))/Double(NSEC_PER_SEC)) {
            //code
            self.navigationController?.popToRootViewController(animated: true)
        }

    }
}

// MARK:- 登陆
extension MeBaseViewController {
    
    /**
     ## 登陆
     主要实现了登陆封装逻辑
     
     - tfNum    电话号码
     - tfPass   密码
     */
    func login(tfNum : UITextField,tfPass : UITextField) -> Void {
        
        print("\((#file as NSString).lastPathComponent):(\(#line)):(\("单机登陆")))")
        if tfNum.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfNumIsNull)
            return
            
        } else if Encryption.checkTelNumber(tfNum.text) == false {
            MBManager.showBriefAlert(tfNumNotCor)
            return
        } else if tfNum.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfPassNull)
            
        } else if Encryption.checkTelNumber(tfNum.text) == true {
            
            
            let params = ["phone" : tfNum.text!,
                          "password" : Encryption.md5Encrypt(with: tfPass.text),
                          "deviceid": deviceID,
                          "devtype" : deviceTpye] as [String : Any]
            print(params)
            
            MBManager.showBriefMessage("登陆中...", in: self.view)
            postWithPath(path: loginUrl, paras: params, success: { (response) in
                
                //判读返回值是否为空
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                
                //提取提示语
                let alertmsg = dic["resultmsg"] as! String
                
                print(dic)
                
                    if alertmsg == "帐号与密码不匹配" {
                        MBManager.showBriefAlert(passAndAccountNot)
                    } else if alertmsg == "缺少手机号参数" {
                        MBManager.showBriefAlert(tfNumNotCor)
                    } else if alertmsg == "恭喜您登录成功" {
                        
                        //本地存储
                        localSave.set(tfNum.text!, forKey: localName)
                        localSave.set(tfPass.text!, forKey: localPass)
                        localSave.synchronize()
                        
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(loginSuccess)
                        

                        guard let dataSource = (dic["data"] as? NSDictionary) else {
                            return
                        }
                        
                        if dataSource.count == 0 {
                            return
                        } else {
                            //存储用户信息
                            let token = dataSource["token"] as! String
                            
                            print(token)
                            
                            localSave.set(token, forKey: userToken)
                            
                            localSave.synchronize()
                            
                            //返回主界面
                            self.backToMain()
                        }

                    }

            }, failure: { (error) in
                print("\((#file as NSString).lastPathComponent):(\(#line))")
                print(error)
                MBManager.showBriefAlert("网络异常")

            })
        }
        
 
    }
}

// MARK:- 注册
extension MeBaseViewController {
    
    /**
     ## 注册
     封装了注册逻辑
     
     - tfNum            电话号码
     - tfAuto           验证码
     - tfPass           密码
     - tfconfirmPass    确认密码
     */
    func rigister(tfNum : UITextField,tfAuto : UITextField, tfPass : UITextField,tfconfirmPass : UITextField) -> Void {
            print("\((#file as NSString).lastPathComponent):(\(#line)):(\("注册")))")
        
        let bool = localSave.bool(forKey: agreeLaw)
        
        if tfNum.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfNumIsNull)
            
        } else if tfAuto.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfAutoNull)
            
        } else if tfPass.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfPassNull)
            
        } else if tfconfirmPass.text?.characters.count == 0 {
            MBManager.showBriefAlert(confirPassNotNull)
            
        } else if Encryption.checkTelNumber(tfNum.text) == false {
            MBManager.showBriefAlert(tfNumNotCor)
            
        } else if tfPass.text != tfconfirmPass.text {
            MBManager.showBriefAlert(passTwoChekc)
            
        } else if Encryption.checkTelNumber(tfNum.text) == true && bool == false {
            
            /**
             注册成功，恭喜您成为一元预购的新成员
             缺少验证码
             短信验证码错误
             手机号已被注册
             缺少手机号参数或手机格式错误或为11位数字
             */
            let params = ["deviceid":deviceID,
                          "devtype": deviceTpye,
                          "username" : tfNum.text!,
                          "phone":tfNum.text!,
                          "password":Encryption.md5Encrypt(with:tfPass.text) as Any,
                          "code":tfAuto.text!] as [String : Any]
            
            MBManager.showPermanentAlert("注册中...")
            postWithPath(path: rigisterUrl, paras: params, success: { (response) in
                
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                
                //提取提示语
                let alertmsg = dic["resultmsg"] as! String
                
                print(dic)


                if alertmsg == "缺少手机号参数或手机格式错误或为11位数字" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(tfNumNotCor)
                } else if alertmsg == "短信验证码错误" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(authNumWrong)
                } else if alertmsg == "手机号已被注册"{
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(numUsed)

                } else if alertmsg == "注册成功，恭喜您成为一元预购的新成员" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(rigSuccess)
                    
                    //返回主界面
                    self.backToMain()
                }
                
            }, failure: { (error) in
                print("\((#file as NSString).lastPathComponent):(\(#line))")
                print(error)
                MBManager.hideAlert()
                MBManager.showBriefAlert("网络异常")
            })
        }
        else {
            MBManager.showBriefAlert(agressLawing)
        }
    
    }
}


// MARK:- 发送注册验证码
extension MeBaseViewController {
    /**
     ## 发送注册验证码
     封装发送验证码业务逻辑
     
     - tfNum    电话号码
     */
    func sendRigisterMsg(tfNum : UITextField) -> Void {
        
        //检查验证码是否为空
        if tfNum.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfNumIsNull)
        } else if Encryption.checkTelNumber(tfNum.text) == false {
            
            MBManager.showBriefAlert(tfNumNotCor)
        } else if Encryption.checkTelNumber(tfNum.text) == true {
            
            
            let params = ["type":1,
                          "phone":tfNum.text!] as [String : Any]
            print(params)

            
            
            MBManager.showPermanentMessage("发送中...", in: self.view)
            postWithPath(path: sendMsgUrl, paras: params, success: { (response) in
  
                
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                //提取提示语
                let alertmsg = dic["resultmsg"] as! String

                
                    if alertmsg == "手机号已被注册" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(numUsed)
                        return
                    } else if alertmsg == "成功" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(msgSended)
                    } else if alertmsg == "触发业务流控" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(msgSengWrong)
                    }  else if alertmsg == "发送短信失败" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(msgSengWrong)
                }
                
            }, failure: { (error) in
                print("\((#file as NSString).lastPathComponent):(\(#line))")
                print(error)
                MBManager.hideAlert()
                MBManager.showBriefAlert("网络异常")

            })
        }
    }
}

// MARK:- 发送忘记密码验证码
extension MeBaseViewController {
    
    /**
     ## 发送忘记密码验证码
     封装发送验证码业务逻辑
     
     - tfNum    电话号码
     */
    func sendForgetAuto(tfNum : UITextField) -> Void {
        //检查验证码是否为空
        if tfNum.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfNumIsNull)
        } else if Encryption.checkTelNumber(tfNum.text) == false {
            
            MBManager.showBriefAlert(tfNumNotCor)
        } else if Encryption.checkTelNumber(tfNum.text) == true {
            
            
            let params = ["type":2,
                          "phone":tfNum.text!] as [String : Any]
            print(params)
            
            
            MBManager.showPermanentMessage("发送中...", in: self.view)
            postWithPath(path: sendMsgUrl, paras: params, success: { (response) in
                //判读返回值是否为空
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                //提取提示语
                let alertmsg = dic["resultmsg"] as! String

                if alertmsg == "手机号已被注册" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(numUsed)
                    return
                } else if alertmsg == "成功" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(msgSended)
                } else if alertmsg == "触发业务流控" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(msgSengWrong)
                } else if alertmsg == "发送短信失败" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert(msgSengWrong)
                }

            }, failure: { (error) in
                print(error.localizedDescription)
            })
            
        }

    }
}


// MARK:- 忘记密码
extension MeBaseViewController {
    /**
     ## 忘记密码
     封装忘记密码业务逻辑
     
     - tfNum            电话号码
     - tfPass           密码
     - tfConfirmPass    确认密码
     */
    func forgetPass(tfNum : UITextField,tfAuto : UITextField,tfPass : UITextField,tfConfirmPass : UITextField) -> Void {
        
        if tfNum.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfNumIsNull)
            
        } else if tfAuto.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfAutoNull)
            
        } else if tfPass.text?.characters.count == 0 {
            MBManager.showBriefAlert(tfPassNull)
            
        } else if tfConfirmPass.text?.characters.count == 0 {
            MBManager.showBriefAlert(confirPassNotNull)
            
        } else if Encryption.checkTelNumber(tfNum.text) == false {
            MBManager.showBriefAlert(tfNumNotCor)
            
        } else if tfPass.text != tfConfirmPass.text {
            MBManager.showBriefAlert(passTwoChekc)
            
        } else if Encryption.checkTelNumber(tfNum.text) == true {
            let params = ["code":tfAuto.text!,
                          "newpwd":Encryption.md5Encrypt(with: tfPass.text),
                          "phone":tfNum.text!] as [String : Any]
            print(params)
            
            MBManager.showPermanentAlert("密码修改中...")
            postWithPath(path: forgetPassUrl, paras: params, success: { (response) in
                    /**
                      缺少手机号参数或手机格式错误或不为11位数字
                      短信验证码错误
                      缺少验证码参数
                      手机号不存在
                      你的密码修改成功
                      触发业务流控
                      */
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                //提取提示语
                let alertmsg = dic["resultmsg"] as! String

    
                    if alertmsg == "缺少手机号参数或手机格式错误或不为11位数字" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(tfNumNotCor)
    
                    } else if alertmsg == "短信验证码错误" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(tfAuthWrong)
    
                    } else if alertmsg == "触发业务流控"{
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(msgSengWrong)
                        
                    } else if alertmsg == "手机号不存在"{
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(phoneNotExist)

                    } else if alertmsg == "你的密码修改成功"{
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(changePasSuccess)
                        
                        //返回主界面
                        self.backToMain()
                    }
                    

            }, failure: { (error) in
                print("\((#file as NSString).lastPathComponent):(\(#line))")
                print(error)
                MBManager.hideAlert()
                MBManager.showBriefAlert("网络异常")
            })
        }

    }
}

// MARK:- 修改密码
extension MeBaseViewController {
    /**
     ## 修改密码
     封装修改密码业务逻辑
     
     - tfOldPass    旧密码
     - tfNewPass    新密码
     */
    func changePassSEL(tfOldPass :UITextField,tfNewPass :UITextField) -> Void {
        
        
        if localSave.object(forKey: userToken) as? String != nil {
            let token = localSave.object(forKey: userToken) as! String
            print(token)
            if tfOldPass.text?.characters.count == 0 {
                MBManager.showBriefAlert(tfPassNull)
                
            } else if tfNewPass.text?.characters.count == 0 {
                MBManager.showBriefAlert(passNewNil)
            } else {
                
                
                let param = ["oldpwd" : Encryption.md5Encrypt(with: tfOldPass.text),
                             "newpwd" : Encryption.md5Encrypt(with: tfNewPass.text),
                             "token": token,
                             ] as [String : Any]
                
                print(param)
                
                
                MBManager.showBriefMessage("密码修改中...", in: self.view)
                postWithPath(path: xgPass, paras: param, success: { (response) in
                    guard let dic = response as? NSDictionary else {
                        return
                    }
                    
                    print(dic)
                    //提取提示语
                    let alertmsg = dic["resultmsg"] as! String


                    
                    if alertmsg == "原始密码错误" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(passNotCor)
                    } else if alertmsg == "该账号已在异地登录，请重新登录" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(loginError)
                        
                        //返回主界面
                        self.backToMain()
                    } else if alertmsg == "密码修改成功" {
                        MBManager.hideAlert()
                        MBManager.showBriefAlert(changePassSuccess)
                        //返回主界面
                        self.backToMain()
                    }
                        
                }, failure: { (error) in
                    print("\((#file as NSString).lastPathComponent):(\(#line))")
                    print(error)
                    MBManager.hideAlert()
                    MBManager.showBriefAlert("网络异常")
                })
                
            }
            
        } else {
            print("token不存在")
            return
        }
    }
}



